package com.ly.mpayment.persist.hibernate;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.QueryParameterException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.ly.mpayment.core.util.ReflectionUtils;

/**
 * 封装Hibernate原生API的DAO泛型基类.
 * <p/>
 * 可在Service层直接使用,也可以扩展泛型DAO子类使用.
 * 参考Spring2.5自带的Petlinc例子,取消了HibernateTemplate,直接使用Hibernate原生API.
 *
 *
 * @param <T>
 *            DAO操作的对象类型
 * @param <PK>
 *            主键类型
 */
@SuppressWarnings("unchecked")
@Transactional
public class SimpleHibernateDao<T, PK extends Serializable> {
	protected Log logger = LogFactory.getLog(getClass());

	protected SessionFactory sessionFactory;

	protected Class<T> entityClass;

	/**
	 * 用于Dao层子类使用的构造函数. 通过子类的泛型定义取得对象类型Class. eg. public class UserDao extends
	 * SimpleHibernateDao<User, Long>
	 */
	public SimpleHibernateDao() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
	}

	/**
	 * 用于用于省略Dao层, 在Service层直接使用通用SimpleHibernateDao的构造函数. 在构造函数中定义对象类型Class.
	 * eg. SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User,
	 * Long>(sessionFactory, User.class);
	 */
	public SimpleHibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
		this.sessionFactory = sessionFactory;
		this.entityClass = entityClass;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 采用@Autowired按类型注入SessionFactory,当有多个SesionFactory的时候Override本函数.
	 */
	@Autowired
	public void setSessionFactory(final SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 取得当前Session.
	 */
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 保存新增或修改的对象.
	 */
	public T save(final T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().saveOrUpdate(entity);
		logger.debug("save entity:" + entity);
		return entity;
	}

	/**
	 * 新增\修改
	 *
	 * @param entity
	 * @return
	 */
	public T saveOrUpdate(T entity) {
		try {
			getSession().saveOrUpdate(entity);
			return entity;
		} catch (Exception e) {
			logger.error("exception save failure !", e);
		}
		return null;
	}

	public T updateEntity(T entity) {
		try {
			getSession().update((entity));
			return entity;
		} catch (Exception e) {
			logger.error("exception save failure !", e);
		}
		return null;
	}

	public T updateEntityShopInfo(T entity) {
		try {
			getSession().update((entity));
			return entity;
		} catch (Exception e) {
			logger.error("exception save failure !", e);
		}
		return null;
	}
	/**
	 * 删除对象.
	 *
	 * @param entity
	 *            对象必须是session中的对象或含id属性的transient对象.
	 */
	public void delete(final T entity) {
		//Assert.notNull(entity, "entity不能为空");
		if(entity != null){
			getSession().delete(entity);
		}
		logger.debug("delete entity:" + entity);
	}

	/**
	 * 按id删除对象.
	 */
	public void delete(final PK id) {
		Assert.notNull(id, "id不能为空");
		delete(get(id));
		logger.debug("delete entity " + entityClass.getSimpleName() + "id is " + id);
	}

	/**
	 * 根据id查询对象
	 *
	 * @param ids
	 *            id值
	 * @param classType
	 *            查询映射类
	 * @return Criteria
	 *
	 *         列：List list = findById(1,new User().getClass()).list();
	 */
	@SuppressWarnings("rawtypes")
	public Criteria findById(Object ids, Class classType) {

		Criteria criteria = this.getSession().createCriteria(classType).add(Restrictions.eq("id", ids));

		return criteria;
	}

	/**
	 * 按id获取对象.
	 */
	public T get(final PK id) {
		Assert.notNull(id, "id不能为空");
		return (T) getSession().get(entityClass, id);
	}

	/**
	 * 按id获取对象.
	 */
	public T load(final PK id) {
		Assert.notNull(id, "id不能为空");
		return (T) getSession().load(entityClass, id);
	}

	/**
	 * 获取全部对象.
	 */
	public List<T> getAll() {
		return find();
	}

	/**
	 * 获取全部对象, 支持按属性行序.
	 */
	public List<T> getAll(String orderByProperty, boolean isAsc) {
		Criteria c = createCriteria();
		if (isAsc) {
			c.addOrder(Order.asc(orderByProperty));
		} else {
			c.addOrder(Order.desc(orderByProperty));
		}
		return c.list();
	}

	/**
	 * 按属性查找对象列表,匹配方式为相等.
	 */
	public List<T> findBy(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, value);
		return find(criterion);
	}

	/**
	 * 按属性查找唯一对象,匹配方式为相等.
	 */
	public T findByUnique(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, value);
		T result = (T) createCriteria(criterion).uniqueResult();
		return result;
	}

	/**
	 * 按HQL查询对象列表.
	 *
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public List<T> find(final String hql, final Object... values) {
		return createQuery(hql, values).list();
	}

	/**
	 * 按HQL查询对象列表.
	 *
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public List<T> find(final String hql) {
		return createQuery(hql).list();
	}

	/**
	 * 按HQL查询对象列表.
	 *
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public List<T> find(final String hql, final Map<String, Object> values) {
		this.logger.debug(values + "-----hql-------------------------" + hql);
		Query query = createQuery(hql, values);
		return query.list();
	}

	/**
	 * 按HQL查询唯一对象.
	 *
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public T findUnique(final String hql, final Object... values) {
		return (T) createQuery(hql, values).uniqueResult();
	}

	/**
	 * 按HQL查询唯一对象.
	 *
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public T findUnique(final String hql, final Map<String, Object> values) {
		return (T) createQuery(hql, values).uniqueResult();
	}

	/**
	 * 按HQL查询Integer类型结果.
	 */
	public Integer findInt(final String hql, final Object... values) {
		return (Integer) findUnique(hql, values);
	}

	public Integer findInt(final String hql, final Map<String, Object> values) {
		return (Integer) findUnique(hql, values);
	}

	/**
	 * 按HQL查询Long类型结果.
	 */
	public Long findLong(final String hql, final Object... values) {
		return (Long) findUnique(hql, values);
	}

	/**
	 * 按HQL查询Long类型结果.
	 */
	public Long findLong(final String hql, final Map<String, Object> values) {
		return (Long) findUnique(hql, values);
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 */
	public int batchExecute(final String hql, final Object... values) {
		return createQuery(hql, values).executeUpdate();
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 */
	public int batchExecute(final String hql, final Map<String, Object> values) {
		return createQuery(hql, values).executeUpdate();
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 * <p/>
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 *
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public Query createQuery(final String queryString, final Object... values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = getSession().createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query;
	}

	/**
	 * 根据id值删除数据
	 *
	 * @param deleteString
	 * @param ids
	 */
	public void deleteQuery(final String deleteString, final String[] ids) {
		// 组合删除条件
		String deleteParams = "";
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				if (i + 1 != ids.length) {
					deleteParams = deleteParams + " id = " + ids[i] + " or ";
				} else if (i + 1 == ids.length) {
					deleteParams = deleteParams + " id = " + ids[i];
				}
			}
		}
		String deleteHql = deleteString + " where " + deleteParams;
		getSession().createQuery(deleteHql).executeUpdate();

	}

	/**
	 * 根据id值删除数据,不使用json
	 *
	 * @jiangyu this is my own method
	 * @param deleteString
	 * @param ids
	 */
	public void deleteQuery(final String deleteString, String id) {
		// 组合删除条件
		String[] ids = null;
		String s = ",";
		if (id.indexOf(s) >= 0) {
			ids = id.split(s);
		}
		String deleteParams = "";
		if (ids.length > 0) {
			for (int i = 0; i < ids.length; i++) {
				if (i + 1 != ids.length) {
					deleteParams = deleteParams + " id = " + ids[i] + " or ";
				} else if (i + 1 == ids.length) {
					deleteParams = deleteParams + " id = " + ids[i];
				}
			}
		}
		String deleteHql = deleteString + " where " + deleteParams;
		getSession().createQuery(deleteHql).executeUpdate();
	}

	/**
	 * 删除
	 * @param deleteString
	 */
	public void deleteQuery(final String deleteString) {
		getSession().createSQLQuery(deleteString).executeUpdate();
	}

	/**
	 * jiangyu This method is of my own
	 *
	 * @param deleteString
	 * @param ids
	 * @param deleteFiled
	 *            根据指定字段删除
	 */
	public void deleteByQuery(final String deleteString, final String[] attribute, final String deleteFileds) {
		// 组合删除条件
		String deleteParams = "";
		String deleteFiled = deleteFileds == null ? "" : deleteFileds;
		if (attribute.length > 0 && !deleteFiled.equals("")) {
			for (int i = 0; i < attribute.length; i++) {
				if (i + 1 != attribute.length) {
					deleteParams = deleteParams + deleteFiled + " = " + attribute[i] + " or ";
				} else if (i + 1 == attribute.length) {
					deleteParams = deleteParams + deleteFiled + " = " + attribute[i];
				}
			}
		}
		String deleteHql = deleteString + " where " + deleteParams;
		getSession().createQuery(deleteHql).executeUpdate();

	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 *
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	@SuppressWarnings("rawtypes")
	public Query createQuery(final String queryString, final Map<String, Object> values) {
		logger.debug("query:" + queryString);
		Assert.hasText(queryString, "queryString不能为空");
		Query query = getSession().createQuery(queryString);

		Set keys = values.keySet();
		Iterator it = keys.iterator();
		while (it.hasNext()) {
			String keyValue = (String) it.next();
			if (!keyValue.equalsIgnoreCase("start") && !keyValue.equalsIgnoreCase("limit")) {
				String key = keyValue.substring(1);
				Object params = values.get(keyValue);
				try {
					if (params != null) {
						if (params.getClass().getName().equals(ArrayList.class.getName())) {
							List list = new ArrayList();
							list = (List) params;
							query.setParameterList(key, list);
						} else {
							query.setParameter(key, params);
						}
					}
				} catch (QueryParameterException e) {
					logger.error("exception in createQuery:", e);
					continue;
				}
			} else {
				// 判断是否有分页参数
				query.setFirstResult((Integer) values.get("start"));
				query.setMaxResults((Integer) values.get("limit"));
			}
		}
		return query;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 *
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	@SuppressWarnings("rawtypes")
	public Query countQuery(final String queryString, final Map<String, Object> values) {
		logger.debug("query:" + queryString);
		Assert.hasText(queryString, "queryString不能为空");
		Query query = getSession().createQuery(queryString);

		Set keys = values.keySet();
		Iterator it = keys.iterator();
		while (it.hasNext()) {
			String keyValue = (String) it.next();
			if (!keyValue.equalsIgnoreCase("start") && !keyValue.equalsIgnoreCase("limit")) {
				String key = keyValue.substring(1);
				Object params = values.get(keyValue);
				try {
					if (params != null) {
						query.setParameter(key, params);
					}
				} catch (QueryParameterException e) {
					logger.error("exception in createQuery:", e);
					continue;
				}
			}
		}
		return query;
	}

	/**
	 * 按Criteria查询对象列表.
	 *
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public List<T> find(final Criterion... criterions) {
		return createCriteria(criterions).list();
	}

	/**
	 * 按Criteria查询唯一对象.
	 *
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public T findUnique(final Criterion... criterions) {
		return (T) createCriteria(criterions).uniqueResult();
	}

	/**
	 * 根据Criterion条件创建Criteria.
	 * <p/>
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 *
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public Criteria createCriteria(final Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(entityClass);
		for (Criterion c : criterions) {
			criteria.add(c);
		}
		return criteria;
	}

	/**
	 * 初始化对象. 使用load()方法得到的仅是对象Proxy, 在传到View层前需要进行初始化.
	 * 只初始化entity的直接属性,但不会初始化延迟加载的关联集合和属性. 如需初始化关联属性,可实现新的函数,执行:
	 * Hibernate.initialize(user.getRoles())，初始化User的直接属性和关联集合.
	 * Hibernate.initialize(user.getDescription())，
	 * 初始化User的直接属性和延迟加载的Description属性.
	 */
	public void initEntity(T entity) {
		Hibernate.initialize(entity);
	}

	/**
	 * @see #initEntity(Object)
	 */
	public void initEntity(List<T> entityList) {
		for (T entity : entityList) {
			Hibernate.initialize(entity);
		}
	}

	/**
	 * 为Query添加distinct transformer.
	 */
	public Query distinct(Query query) {
		query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		return query;
	}

	/**
	 * 为Criteria添加distinct transformer.
	 */
	public Criteria distinct(Criteria criteria) {
		criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		return criteria;
	}

	/**
	 * 通过Set将不唯一的对象列表唯一化. 主要用于HQL/Criteria预加载关联集合形成重复记录,又不方便使用distinct查询语句时.
	 */
	public <X> List<X> distinct(List<X> list) {
		Set<X> set = new LinkedHashSet<X>(list);
		return new ArrayList<X>(set);
	}

	/**
	 * 取得对象的主键名.
	 */
	public String getIdName() {
		ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
		Assert.notNull(meta, "Class " + entityClass.getSimpleName() + " not define in HibernateSessionFactory.");
		return meta.getIdentifierPropertyName();
	}
}
